package com.ysd.lis.service.inv.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.SysOrgDepartment;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.inv.*;
import com.ysd.lis.mapper.inv.InvOrderInfoMapper;
import com.ysd.lis.mapper.inv.InvOrderReagentMapper;
import com.ysd.lis.mapper.inv.InvReagentStockMapper;
import com.ysd.lis.request.inv.*;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysRuleSetService;
import com.ysd.lis.service.inv.InvOrderInfoService;
import com.ysd.lis.service.inv.InvOrderReagentService;
import com.ysd.lis.service.inv.InvReagentStockService;
import com.ysd.lis.service.inv.InvTransferTypeService;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单信息 服务实现类
 * </p>
 *
 * @author WH
 * @since 2024-09-19
 */
@Service
public class InvOrderInfoServiceImpl extends ServiceImpl<InvOrderInfoMapper, InvOrderInfo> implements InvOrderInfoService {
    @Autowired
    InvOrderInfoMapper invOrderInfoMapper;
    @Autowired
    InvOrderInfoService invOrderInfoService;
    @Autowired
    InvOrderReagentService invOrderReagentService;
    @Autowired
    InvOrderReagentMapper invOrderReagentMapper;

    @Autowired
    InvTransferTypeService transferTypeService;
    @Autowired
    SysRuleSetService sysRuleSetService;
    @Autowired
    InvReagentStockService invReagentStockService;
    @Autowired
    SysBasDictDetailService sysBasDictDetailService;
    @Autowired
    InvReagentStockMapper invReagentStockMapper;

    @Override
    public Result findOrderInfoList(InvOrderParam param) {

        MPJLambdaWrapper<InvOrderInfo> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(InvOrderInfo.class)
                .selectAs(SysOrgDepartment::getName, InvOrderInfo::getReceiveDeptNa)
                .leftJoin(SysOrgDepartment.class, p -> p.eq(SysOrgDepartment::getCode, InvOrderInfo::getReceiveDept).eq(SysOrgDepartment::getOrgId, InvOrderInfo::getOrgId).eq(SysOrgDepartment::getDelFlag, 0))
                .eq(InvOrderInfo::getDelFlag, 0);
        if (StringUtils.isNotBlank(param.getSearchValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(InvOrderInfo::getOutOrderNumber, param.getSearchValue()).or().like(InvOrderInfo::getInvoiceNumber, param.getSearchValue()).or().like(InvOrderInfo::getPurOrderNumber, param.getSearchValue()));
        }
        if (ToolsUtils.isNotEmpty(param.getWorkGroup())) {
            lambdaQueryWrapper.eq(InvOrderInfo::getWorkGroup, param.getWorkGroup());
        }
        if (ToolsUtils.isNotEmpty(param.getTransferType())) {
            lambdaQueryWrapper.eq(InvOrderInfo::getTransferType, param.getTransferType());
        } else {
            if (ToolsUtils.isNotEmpty(param.getTransferTypes())) {
                String transferTypes = param.getTransferTypes();
                String[] split = transferTypes.split(",");
                lambdaQueryWrapper.in(InvOrderInfo::getTransferType, split);
            }
        }
        if (ToolsUtils.isNotEmpty(param.getOrderStatus())) {
            lambdaQueryWrapper.eq(InvOrderInfo::getOrderStatus, param.getOrderStatus());
        }
        if (ToolsUtils.isNotEmpty(param.getTransferNo())) {
            lambdaQueryWrapper.like(InvOrderInfo::getTransferNo, param.getTransferNo());
        }
        String documentDateBegin = param.getDocumentDateBegin();
        if (ToolsUtils.isNotEmpty(documentDateBegin)) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = dateFormat.parse(documentDateBegin);
                Timestamp timestampBeg = new Timestamp(date.getTime());
                lambdaQueryWrapper.ge(InvOrderInfo::getDocumentDate, timestampBeg);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        String documentDateEnd = param.getDocumentDateEnd();

        if (ToolsUtils.isNotEmpty(documentDateEnd)) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = dateFormat.parse(documentDateEnd);
                Timestamp timestampEnd = new Timestamp(date.getTime());
                lambdaQueryWrapper.le(InvOrderInfo::getDocumentDate, timestampEnd);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        lambdaQueryWrapper.orderByDesc(InvReagent::getCreateTime);
        List<InvOrderInfo> orderInfoList = invOrderInfoMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功", orderInfoList);
    }

    @Override
    public Result findOrderInfoListByAllot(InvOrderParam param) {
        // 使用 Stream API 转换为 List
        String[] array = {"R40", "C50"};
        List<String> list = Arrays.stream(array).collect(Collectors.toList());
        MPJLambdaWrapper<InvOrderInfo> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(InvOrderInfo.class).eq(InvOrderInfo::getDelFlag, 0).in(InvOrderInfo::getTransferType, list);
        if (StringUtils.isNotBlank(param.getSearchValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(InvOrderInfo::getOutOrderNumber, param.getSearchValue()).or().like(InvOrderInfo::getInvoiceNumber, param.getSearchValue()).or().like(InvOrderInfo::getPurOrderNumber, param.getSearchValue()));
        }
        if (ToolsUtils.isNotEmpty(param.getOrderStatus())) {
            lambdaQueryWrapper.eq(InvOrderInfo::getOrderStatus, param.getOrderStatus());
        }
        if (ToolsUtils.isNotEmpty(param.getTransferNo())) {
            lambdaQueryWrapper.like(InvOrderInfo::getTransferNo, param.getTransferNo());
        }
        String documentDateBegin = param.getDocumentDateBegin();
        if (ToolsUtils.isNotEmpty(documentDateBegin)) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = dateFormat.parse(documentDateBegin);
                Timestamp timestampBeg = new Timestamp(date.getTime());
                lambdaQueryWrapper.ge(InvOrderInfo::getDocumentDate, timestampBeg);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        String documentDateEnd = param.getDocumentDateEnd();

        if (ToolsUtils.isNotEmpty(documentDateEnd)) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = dateFormat.parse(documentDateEnd);
                Timestamp timestampEnd = new Timestamp(date.getTime());
                lambdaQueryWrapper.le(InvOrderInfo::getDocumentDate, timestampEnd);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        lambdaQueryWrapper.orderByDesc(InvReagent::getCreateTime);
        List<InvOrderInfo> orderInfoList = invOrderInfoMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功", orderInfoList);
    }

    @Override
    public Result batchDeleteInvOrderInfoList(InvOrderDto dto) {
        List<InvOrderInfo> invOrderInfoList = dto.getInvOrderInfoList();
        List<String> ids = invOrderInfoList.stream().map(InvOrderInfo::getId).collect(Collectors.toList());
        boolean b = this.removeByIds(ids);

        //删除明细
        if (b) {
            LambdaQueryWrapper<InvOrderReagent> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(InvOrderReagent::getDelFlag, 0);
            lambdaQueryWrapper.in(InvOrderReagent::getOrderInfoId, ids);
            invOrderReagentMapper.delete(lambdaQueryWrapper);
            return Result.succ(1, "删除成功", null);
        } else {
            return Result.fail(400, "删除失败", "");
        }
    }

    @Override
    public Result batchCheckInStock(InvOrderDto dto) {
        //批量验收入库
        List<InvOrderInfo> invOrderInfoList = dto.getInvOrderInfoList();
        List<String> ids = invOrderInfoList.stream().map(InvOrderInfo::getId).collect(Collectors.toList());

        //根据订单id集合查出所有的订单明细
        MPJLambdaWrapper<InvOrderReagent> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(InvOrderReagent.class).selectAs("o", InvOrderInfo::getTarStoreCode, InvOrderReagent::getTarStoreCode).selectAs("r", InvReagent::getManufacturerNo, InvOrderReagent::getManufacturerNo).selectAs("r", InvReagent::getIsSingleBarcode, InvOrderReagent::getIsSingleBarcode).selectAs("r", InvReagent::getProUnitRatio, InvOrderReagent::getProUnitRatio).selectAs("r", InvReagent::getStockUnitRatio, InvOrderReagent::getStockUnitRatio).selectAs("r", InvReagent::getStockUnit, InvOrderReagent::getStockUnit).innerJoin(InvOrderInfo.class, "o", p -> p.eq(InvOrderInfo::getId, InvOrderReagent::getOrderInfoId).eq(InvOrderInfo::getOrderStatus, "5").eq(InvOrderInfo::getDelFlag, 0)).leftJoin(InvReagent.class, "r", p -> p.eq(InvReagent::getReaNo, InvOrderReagent::getReaNo).eq(InvReagent::getDelFlag, 0)).in(InvOrderReagent::getOrderInfoId, ids).eq(InvOrderReagent::getDelFlag, 0).orderByAsc(InvOrderReagent::getOrderInfoId);
        List<InvOrderReagent> itemList = invOrderReagentMapper.selectList(queryWrapper);

        List<InvReagentStock> invReagentStockList = new ArrayList<>();
        //循环入库
        for (InvOrderReagent orderReagent : itemList) {
            Boolean isSingleBarcode = orderReagent.getIsSingleBarcode();
            Integer proUnitRatio = orderReagent.getProUnitRatio();
            Integer stockUnitRatio = orderReagent.getStockUnitRatio();
            //采购系数/库存系数*库存数量
            Double quantity = orderReagent.getAmount().doubleValue() * (proUnitRatio / stockUnitRatio);
            String stockUnit = orderReagent.getStockUnit();

            if (isSingleBarcode) {
                int q = quantity.intValue();
                for (int i = 0; i < q; i++) {
                    InvReagentStock invReagentStock = new InvReagentStock();
                    invReagentStock.setStoreCode(orderReagent.getTarStoreCode());
                    invReagentStock.setReaNo(orderReagent.getReaNo());
                    invReagentStock.setManufacturerNo(orderReagent.getManufacturerNo());
                    invReagentStock.setQuantity(new Double(1));
                    invReagentStock.setInQuantity(new Double(1));
                    invReagentStock.setOutQuantity(new Double(0));
                    invReagentStock.setBatchNum(orderReagent.getBatchNum());
                    invReagentStock.setProduceDate(orderReagent.getProduceDate());
                    invReagentStock.setExpiryDate(orderReagent.getExpiryDate());
                    //nvReagentStock.setUniqueCode();
                    invReagentStock.setPrice(orderReagent.getCostPrice().doubleValue());
                    invReagentStock.setCosts(orderReagent.getCosts().doubleValue());
                    invReagentStock.setUnit(stockUnit);
                    invReagentStock.setOrderInfoId(orderReagent.getOrderInfoId());
                    invReagentStock.setOrderReagentId(orderReagent.getId());
                    if (ToolsUtils.isNotEmpty(orderReagent.getSeq())) {
                        invReagentStock.setSeq(orderReagent.getSeq().intValue());
                    }
                    invReagentStockList.add(invReagentStock);
                }

            } else {
                InvReagentStock invReagentStock = new InvReagentStock();
                invReagentStock.setStoreCode(orderReagent.getTarStoreCode());
                invReagentStock.setReaNo(orderReagent.getReaNo());
                invReagentStock.setManufacturerNo(orderReagent.getManufacturerNo());
                invReagentStock.setQuantity(quantity);
                invReagentStock.setInQuantity(quantity);
                invReagentStock.setOutQuantity(new Double(0));
                invReagentStock.setBatchNum(orderReagent.getBatchNum());
                invReagentStock.setProduceDate(orderReagent.getProduceDate());
                invReagentStock.setExpiryDate(orderReagent.getExpiryDate());
                //nvReagentStock.setUniqueCode();
                invReagentStock.setPrice(orderReagent.getCostPrice().doubleValue());
                invReagentStock.setCosts(orderReagent.getCosts().doubleValue());
                invReagentStock.setUnit(stockUnit);
                invReagentStock.setOrderInfoId(orderReagent.getOrderInfoId());
                invReagentStock.setOrderReagentId(orderReagent.getId());
                if (ToolsUtils.isNotEmpty(orderReagent.getSeq())) {
                    invReagentStock.setSeq(orderReagent.getSeq().intValue());
                }
                invReagentStockList.add(invReagentStock);
            }
        }
        if (ToolsUtils.isNotEmpty(invReagentStockList)) {
            boolean b = invReagentStockService.saveBatch(invReagentStockList);
            if (b) {
                //批量修改订单状态 改为已验收入库
                for (InvOrderInfo invOrderInfo : invOrderInfoList) {
                    invOrderInfo.setOrderStatus("10");
                }
                boolean b1 = this.updateBatchById(invOrderInfoList);
                return Result.succ(1, "验收成功", null);
            }

        }
        return Result.fail("验收失败");


    }

    @Override
    public Result batchAllotInStock(InvOrderDto dto) {
        //批量验收入库
        List<InvOrderInfo> invOrderInfoList = dto.getInvOrderInfoList();
        List<String> ids = invOrderInfoList.stream().map(InvOrderInfo::getId).collect(Collectors.toList());

        //根据订单id集合查出所有的订单明细
        MPJLambdaWrapper<InvOrderReagent> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(InvOrderReagent.class).selectAs("o", InvOrderInfo::getTarStoreCode, InvOrderReagent::getTarStoreCode).selectAs("o", InvOrderInfo::getTransferNo, InvOrderReagent::getTransferNo).selectAs("rs", InvReagentStock::getQuantity, InvOrderReagent::getAmount).innerJoin(InvOrderInfo.class, "o", p -> p.eq(InvOrderInfo::getId, InvOrderReagent::getOrderInfoId).eq(InvOrderInfo::getOrderStatus, "5").eq(InvOrderInfo::getDelFlag, 0)).leftJoin(InvReagentStock.class, "rs", p -> p.eq(InvReagentStock::getId, InvOrderReagent::getStockId).eq(InvReagentStock::getDelFlag, 0)).in(InvOrderReagent::getOrderInfoId, ids).eq(InvOrderReagent::getDelFlag, 0);
        List<InvOrderReagent> orderReagents = invOrderReagentMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(orderReagents)) {
            return Result.fail("订单下没有需要调拨数据");
        }
        List<String> orderReagentIds = orderReagents.stream().map(InvOrderReagent::getStockId).collect(Collectors.toList());
        List<InvReagentStock> reagentStocks = invReagentStockService.listByIds(orderReagentIds);
        Map<String, List<InvReagentStock>> stringListMap = reagentStocks.stream().collect(Collectors.groupingBy(InvReagentStock::getId));

        List<InvReagentStock> addStockList = new ArrayList<>();
        List<InvReagentStock> updateStockList = new ArrayList<>();

        for (InvOrderReagent invOrderReagent : orderReagents) {
            //目标仓库 新增
            String tarStoreCode = invOrderReagent.getTarStoreCode();
            InvReagentStock stock = stringListMap.get(invOrderReagent.getStockId()).get(0);
            if (stock.getQuantity() == 0.0 || stock.getQuantity() < invOrderReagent.getApplyNum().doubleValue()) {
                return Result.fail("调拨单号:" + invOrderReagent.getTransferNo() + "下" + invOrderReagent.getReaNa() + ",库存不足");
            }
            InvReagentStock tarStock = new InvReagentStock();
            BeanUtil.copyProperties(stock, tarStock);
            tarStock.setId(null);
            tarStock.setOrderInfoId(invOrderReagent.getOrderInfoId());
            tarStock.setOrderReagentId(invOrderReagent.getId());
            tarStock.setStoreCode(tarStoreCode);
            tarStock.setQuantity(invOrderReagent.getApplyNum().doubleValue());
            tarStock.setInQuantity(invOrderReagent.getApplyNum().doubleValue());
            tarStock.setCosts(invOrderReagent.getApplyNum().doubleValue() * invOrderReagent.getCostPrice().doubleValue());
            addStockList.add(tarStock);
            //源仓库 减少
            stock.setQuantity(stock.getQuantity() - invOrderReagent.getApplyNum().doubleValue());
            stock.setOutQuantity(stock.getOutQuantity() + invOrderReagent.getApplyNum().doubleValue());
            updateStockList.add(stock);
        }
        invReagentStockService.saveBatch(addStockList);
        invReagentStockService.updateBatchById(updateStockList);
        for (InvOrderInfo invOrderInfo : invOrderInfoList) {
            SysUser sysUser = RedisUserManager.getUser();
            if (ToolsUtils.isNotEmpty(sysUser)) {
                invOrderInfo.setNotifyPerson(sysUser.getUsername());
            }
            invOrderInfo.setOrderStatus("10");
            invOrderInfo.setNotifyDate(new Timestamp(System.currentTimeMillis()));
        }
        invOrderInfoService.saveOrUpdateBatch(invOrderInfoList);
        return Result.succ(1, "调拨成功", null);
    }

    @Override
    public Result checkOutStock(InvOrderInfo invOrderInfo) {

        List<InvOrderReagent> orderReagents = invOrderInfo.getReagentList();
        if (CollectionUtils.isEmpty(orderReagents)) {
            return Result.fail("订单下没有需要出库数据");
        }
        List<String> orderReagentIds = orderReagents.stream().map(InvOrderReagent::getStockId).collect(Collectors.toList());
        List<InvReagentStock> reagentStocks = invReagentStockService.listByIds(orderReagentIds);
        Map<String, List<InvReagentStock>> stringListMap = reagentStocks.stream().collect(Collectors.groupingBy(InvReagentStock::getId));

        List<InvReagentStock> updateStockList = new ArrayList<>();
        for (InvOrderReagent invOrderReagent : orderReagents) {
            InvReagentStock stock = stringListMap.get(invOrderReagent.getStockId()).get(0);
            if (stock.getQuantity() == 0.0 || stock.getQuantity() < invOrderReagent.getApplyNum().doubleValue()) {
                return Result.fail("出库单号:" + invOrderReagent.getTransferNo() + "下" + invOrderReagent.getReaNa() + ",库存不足");
            }
            //源仓库 减少
            stock.setQuantity(stock.getQuantity() - invOrderReagent.getApplyNum().doubleValue());
            stock.setOutQuantity(stock.getOutQuantity() + invOrderReagent.getApplyNum().doubleValue());
            updateStockList.add(stock);
        }
        boolean b = invReagentStockService.updateBatchById(updateStockList);
        if (b) {

            SysUser sysUser = RedisUserManager.getUser();
            if (ToolsUtils.isNotEmpty(sysUser)) {
                invOrderInfo.setNotifyPerson(sysUser.getUsername());
            }
            invOrderInfo.setOrderStatus("10");
            invOrderInfo.setNotifyDate(new Timestamp(System.currentTimeMillis()));
            this.updateById(invOrderInfo);
            return Result.succ(1, "出库成功", null);

        } else {
            return Result.fail("出库失败");

        }

    }

    @Override
    public Result getInvOrderAgency(InvReagentStockParam param) {
        Map<String, Object> returnMap = new HashMap<>();

        MPJLambdaWrapper<InvOrderInfo> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(InvOrderInfo.class).eq(InvOrderInfo::getOrderStatus, "5").eq(InvOrderInfo::getDelFlag, 0);
        List<InvOrderInfo> orderInfoList = invOrderInfoMapper.selectList(lambdaQueryWrapper);
        //查询所有的流转方式
        List<InvTransferType> transferTypeList = transferTypeService.list(new LambdaQueryWrapper<InvTransferType>().eq(InvTransferType::getDelFlag, 0));
        //入库验收
        List<String> inTransferCodeList = transferTypeList.stream().filter(a -> a.getBusinessType().equals("01") && a.getShowFlag()).map(InvTransferType::getTransferCode).collect(Collectors.toList());
        long inOrderCnt = orderInfoList.stream().filter(a -> inTransferCodeList.contains(a.getTransferType())).count();
        returnMap.put("inOrderCnt", inOrderCnt);
        //调拨入库确认
        long dbInCnt = orderInfoList.stream().filter(a -> a.getTransferType().equals("C50")).count();
        returnMap.put("dbInCnt", dbInCnt);

        //调拨出库确认
        long dbOutCnt = orderInfoList.stream().filter(a -> a.getTransferType().equals("R40")).count();
        returnMap.put("dbOutCnt", dbOutCnt);
        //出库确认

        List<String> outTransferCodeList = transferTypeList.stream().filter(a -> a.getBusinessType().equals("02") && a.getShowFlag()).map(InvTransferType::getTransferCode).collect(Collectors.toList());
        long outOrderCnt = orderInfoList.stream().filter(a -> outTransferCodeList.contains(a.getTransferType())).count();
        returnMap.put("outOrderCnt", outOrderCnt);

        return Result.succ(1, "查询成功", returnMap);
    }

    /*单个商品流程步骤*/
    @Override
    public Result getReagentSteps(GetReagentStepsParam input) {
        if (StringUtils.isBlank(input.getReaNo())) {
            return Result.fail("参数:商品编号为空");
        }
        if (StringUtils.isBlank(input.getBatch())) {
            return Result.fail("参数:批号为空");
        }
        MPJLambdaWrapper<InvOrderInfo> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(InvOrderInfo.class);
        lambdaQueryWrapper.selectAs("itt", InvTransferType::getTransferName, InvOrderInfo::getTransferTypeNa);
        lambdaQueryWrapper.selectAs("itt", InvTransferType::getBusinessType, InvOrderInfo::getBusinessTypeNo);
        lambdaQueryWrapper.selectAs("acter", SysUser::getRealname, InvOrderInfo::getStoragePersonnelNa);
        lambdaQueryWrapper.selectAs("comfr", SysUser::getRealname, InvOrderInfo::getNotifyPersonNa);
        lambdaQueryWrapper.eq(InvOrderInfo::getDelFlag, 0);
        lambdaQueryWrapper.inSql(InvOrderInfo::getId, "SELECT ORDER_INFO_ID FROM INV_ORDER_REAGENT WHERE REA_NO='" + input.getReaNo() + "' and BATCH_NUM='" + input.getBatch() + "'");
        lambdaQueryWrapper.leftJoin(InvTransferType.class, "itt", p -> p.eq(InvOrderInfo::getTransferType, InvTransferType::getTransferCode).isNotNull(InvTransferType::getTransferCode).ne(InvTransferType::getTransferCode, "").eq(InvTransferType::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(SysUser.class, "acter", p -> p.eq(SysUser::getUsername, InvOrderInfo::getStoragePersonnel).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        lambdaQueryWrapper.leftJoin(SysUser.class, "comfr", p -> p.eq(SysUser::getUsername, InvOrderInfo::getNotifyPerson).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        lambdaQueryWrapper.orderByDesc(InvReagent::getCreateTime);
        List<InvOrderInfo> orderInfoList = invOrderInfoMapper.selectList(lambdaQueryWrapper);

        List<Map<String, Object>> tfbtList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("transferBusinessType").getData();

        List<GetReagentStepsDto> resList = new ArrayList<>();
        for (InvOrderInfo m : orderInfoList) {
            if (StringUtils.isNotBlank(m.getBusinessTypeNo()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(tfbtList)) {
                tfbtList.stream().filter(a -> a.get("code").equals(m.getBusinessTypeNo())).findFirst().ifPresent(stringObjectMap -> m.setBusinessTypeNa((String) stringObjectMap.get("name")));
            }
            GetReagentStepsDto op = new GetReagentStepsDto();
            op.setLabel(m.getBusinessTypeNa() + "," + m.getTransferTypeNa());
            Timestamp timestamp = new Timestamp(m.getDocumentDate() == null || BeanUtil.isEmpty(m.getDocumentDate()) ? new Date().getTime() : m.getDocumentDate().getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(timestamp);
            op.setDateStr(formattedDate);
            op.setActorNo(m.getStoragePersonnel());
            op.setActorNa(m.getStoragePersonnelNa());
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDate1 = sdf.format(timestamp);
            op.setActorDt(formattedDate1);
            op.setReagentNo(input.getReaNo());
            op.setReagentNa(input.getReaNa());
            resList.add(op);
        }

        return Result.succ(1, "查询成功", resList);
    }

    @Override
    public Result getBatchSearchChart(FindReagentStockByBatchParam input) {
        MPJLambdaWrapper<InvReagentStock> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(InvReagentStock.class);
        lambdaQueryWrapper.selectAs("r", InvReagent::getReaNa, InvReagentStock::getReaNa);
        lambdaQueryWrapper.selectAs("r", InvReagent::getSpecModel, InvReagentStock::getSpecModel);
        lambdaQueryWrapper.selectAs("r", InvReagent::getExpirDay, InvReagentStock::getExpirDay);

        lambdaQueryWrapper.selectAs("r", InvReagent::getMaxStock, InvReagentStock::getMaxStock);
        lambdaQueryWrapper.selectAs("r", InvReagent::getMiniStock, InvReagentStock::getMiniStock);

        lambdaQueryWrapper.selectAs("ma", InvManufacturer::getManuName, InvReagentStock::getManufacturerName);
        lambdaQueryWrapper.selectAs("ism", InvStoreManage::getStoreName, InvReagentStock::getStoreName);
        lambdaQueryWrapper.leftJoin(InvReagent.class, "r", p -> p.eq(InvReagent::getReaNo, InvReagentStock::getReaNo).eq(InvReagent::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(InvManufacturer.class, "ma", p -> p.eq(InvManufacturer::getManuCode, InvReagentStock::getManufacturerNo).eq(InvManufacturer::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(InvStoreManage.class, "ism", p -> p.eq(InvStoreManage::getStoreCode, InvReagentStock::getStoreCode).eq(InvStoreManage::getDelFlag, 0));
        lambdaQueryWrapper.eq(InvReagentStock::getDelFlag, 0);
        if (StringUtils.isNotBlank(input.getBatch())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(InvReagentStock::getBatchNum, input.getBatch()));
        }
        lambdaQueryWrapper.orderByAsc(InvReagentStock::getBatchNum).orderByDesc(InvReagentStock::getReaNo);
        List<InvReagentStock> materialList = invReagentStockMapper.selectList(lambdaQueryWrapper);

        /*按商品分组*/
        Map<String, List<InvReagentStock>> reaGroup = materialList.stream().collect(Collectors.groupingBy(InvReagentStock::getReaNo));

        GetBatchSearchChartDto resData = new GetBatchSearchChartDto();
        List<String> reaNas = new ArrayList<>();
        List<Double> maxStock = new ArrayList<>();
        List<Double> minStock = new ArrayList<>();
        List<Double> curStock = new ArrayList<>();
        for (Map.Entry<String, List<InvReagentStock>> mm : reaGroup.entrySet()) {
            List<InvReagentStock> lst = mm.getValue();
            String reaNaStr = "";
            for (InvReagentStock op : lst) {
                if (StringUtils.isNotBlank(op.getReaNa()) && StringUtils.isBlank(reaNaStr)) {
                    reaNaStr = op.getReaNa();
                }
                maxStock.add(BeanUtil.isNotEmpty(op.getMaxStock()) ? op.getMaxStock() : 0);
                minStock.add(BeanUtil.isNotEmpty(op.getMiniStock()) ? op.getMiniStock() : 0);
                curStock.add(BeanUtil.isNotEmpty(op.getQuantity()) ? op.getQuantity() : 0);
            }
            reaNas.add(StringUtils.isBlank(reaNaStr) ? "-" : reaNaStr);
        }

        resData.setReaNas(reaNas);
        resData.setMaxStock(maxStock);
        resData.setMinStock(minStock);
        resData.setCurStock(curStock);

        return Result.succ(1, "", resData);
    }

    @Override
    public Result orderFinanceCheck(InvOrderDto dto) {

        //批量验收入库
        List<InvOrderInfo> invOrderInfoList = dto.getInvOrderInfoList();

        //批量修改订单状态 改为已验收入库
        for (InvOrderInfo invOrderInfo : invOrderInfoList) {
            invOrderInfo.setOrderStatus("15");
        }
        boolean b = this.updateBatchById(invOrderInfoList);

        if (b) {
            return Result.succ(1, "验收成功", null);
        } else {
            return Result.fail("验收失败");
        }

    }

    @Override
    public Result addOrderInfo(InvOrderInfo invOrderInfo) {
        List<InvTransferType> transferTypeList = transferTypeService.list(new LambdaQueryWrapper<InvTransferType>().eq(InvTransferType::getDelFlag, 0).eq(InvTransferType::getTransferCode, invOrderInfo.getTransferType()));
        if (CollectionUtils.isNotEmpty(transferTypeList) && StringUtils.isNotBlank(transferTypeList.get(0).getTransferRules())) {
            String transferNo = sysRuleSetService.createRuleCodeList(transferTypeList.get(0).getTransferRules(), 1).get(0);
            invOrderInfo.setTransferNo(transferNo);
        }

        this.save(invOrderInfo);
        List<InvOrderReagent> reagentList = invOrderInfo.getReagentList();
        List<InvOrderReagent> collect = reagentList.stream().filter(item -> item.getAmount().compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());
        collect.forEach(item -> {
            item.setOrderInfoId(invOrderInfo.getId());
        });
        invOrderReagentService.saveBatch(collect);
        return Result.fail(1, "新增成功", invOrderInfo);
    }

    @Override
    public Result editOrderInfo(InvOrderInfo invOrderInfo) {
        this.updateById(invOrderInfo);
        invOrderReagentService.remove(new LambdaQueryWrapper<InvOrderReagent>().eq(InvOrderReagent::getOrderInfoId, invOrderInfo.getId()));
        List<InvOrderReagent> reagentList = invOrderInfo.getReagentList();
        List<InvOrderReagent> collect = reagentList.stream().filter(item -> item.getAmount().compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());
        invOrderReagentService.saveOrUpdateBatch(collect);
        return Result.fail(1, "编辑成功", invOrderInfo);

    }

    @Override
    public Result findOrderInfoAndReagent(InvOrderParam param) {
//        MPJLambdaWrapper<InvOrderInfo> mpjLambdaWrapper = new MPJLambdaWrapper<>();
//        mpjLambdaWrapper
//                .distinct()
//                .selectAll(InvOrderInfo.class)
//                .selectCollection(InvOrderReagent.class, InvOrderInfo::getReagentList)
//                .leftJoin(InvOrderReagent.class, InvOrderReagent::getOrderInfoId, InvOrderInfo::getId)
//                .eq(InvOrderInfo::getDelFlag, 0)
//                .eq(InvOrderInfo::getId, param.getOrderInfoId())
//                .orderByDesc(InvOrderInfo::getCreateTime);
//        InvOrderInfo invOrderInfo = invOrderInfoMapper.selectJoinOne(InvOrderInfo.class, mpjLambdaWrapper);
//        return Result.succ(1, "查询成功！", invOrderInfo);


        InvOrderInfo invOrderInfo = invOrderInfoMapper.selectById(param.getOrderInfoId());
        MPJLambdaWrapper<InvOrderReagent> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(InvOrderReagent.class);
        queryWrapper.selectAs(InvReagent::getProUnit, InvOrderReagent::getProUnit);
        queryWrapper.leftJoin(InvReagent.class, p -> p.eq(InvReagent::getReaNo, InvOrderReagent::getReaNo).eq(InvReagentStock::getDelFlag, 0));
        queryWrapper.eq(InvOrderReagent::getDelFlag, 0);
        queryWrapper.eq(InvOrderReagent::getOrderInfoId, param.getOrderInfoId());
        List<InvOrderReagent> invOrderReagents = invOrderReagentMapper.selectList(queryWrapper);
        invOrderInfo.setReagentList(invOrderReagents);
        return Result.succ(1, "查询成功！", invOrderInfo);
    }

    @Override
    public Result findOrderInfoByAllot(InvOrderParam param) {
        MPJLambdaWrapper<InvOrderInfo> qWrapper = new MPJLambdaWrapper<>();
        qWrapper.selectAll(InvOrderInfo.class);
        qWrapper.selectAs(SysOrgDepartment::getName, InvOrderInfo::getReceiveDeptNa);
        qWrapper.leftJoin(SysOrgDepartment.class, p -> p.eq(SysOrgDepartment::getCode, InvOrderInfo::getReceiveDept).eq(SysOrgDepartment::getOrgId, InvOrderInfo::getOrgId).eq(SysOrgDepartment::getDelFlag, 0));
        qWrapper.eq(InvOrderInfo::getId, param.getOrderInfoId());
        qWrapper.eq(InvOrderInfo::getDelFlag, 0);
        InvOrderInfo invOrderInfo = invOrderInfoMapper.selectOne(qWrapper);

        MPJLambdaWrapper<InvOrderReagent> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(InvOrderReagent.class);
        queryWrapper.selectAs(InvReagentStock::getQuantity, InvOrderReagent::getAmount);
        queryWrapper.leftJoin(InvReagentStock.class, p -> p.eq(InvReagentStock::getId, InvOrderReagent::getStockId).eq(InvReagentStock::getDelFlag, 0));
        queryWrapper.eq(InvOrderReagent::getDelFlag, 0);
        queryWrapper.eq(InvOrderReagent::getOrderInfoId, param.getOrderInfoId());
        List<InvOrderReagent> invOrderReagents = invOrderReagentMapper.selectList(queryWrapper);
        invOrderInfo.setReagentList(invOrderReagents);
        return Result.succ(1, "查询成功！", invOrderInfo);
    }


}
